package service

import (
	"errors"
	"time"
	"yak.admin/src/entity"
	"yak.admin/src/util"
)

const (
	RegisterTemplateId = "SMS_192826494"
	ResetPasswordTemplateId = "SMS_192831494"
)

type SmsService struct {
}

func (service *SmsService) SendCode(phone string, t int, len int, countdown int) error {
	sms := entity.Sms{Phone:phone, Type:t}
	sms.Code = util.GenSmsCode(len)
	db := util.GetMysqlPool().Handler()
	if err := db.Where("phone = ? and type = ?", phone, t).
		FirstOrCreate(&sms).Error; err != nil {
		return err
	}
	if sms.RefreshedAt + int64(sms.Countdown) > time.Now().Unix() {
		return  errors.New("验证码已发送，请稍后再试！")
	}

	sms.RefreshedAt = time.Now().Unix()
	sms.Countdown = countdown
	db.Save(&sms)

	var tpl string
	switch t {
	case entity.SmsCodeRegister:
		tpl = RegisterTemplateId
		break
	case entity.SmsCodeResetPassword:
		tpl = ResetPasswordTemplateId
		break
	}

	if err := util.SendSms(phone, tpl, map[string]string{"code":sms.Code}); err != nil {
		return err
	}
	// fmt.Println("code=", sms.Code)
	return nil
}

func (service *SmsService) VerifyCode(phone string, t int, code string) error {
	var sms entity.Sms
	db := util.GetMysqlPool().Handler()
	if db.Where("phone = ? and type = ?", phone, t).
		First(&sms).RecordNotFound() {
		return errors.New("请发送验证码")
	}
	if int64(sms.Countdown) + sms.RefreshedAt < time.Now().Unix() {
		return errors.New("验证码已过期")
	}
	if sms.Code != code {
		return errors.New("验证码错误")
	}
	db.Delete(&sms)
	return nil
}
